import React, { useEffect, useState, useRef } from "react";
import {
    Text,
    View,
    Image,
    StyleSheet,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Modal,
    ActivityIndicator,
    ScrollView,
    Alert,
    TextInput,
    KeyboardAvoidingView,
    Platform,
    Keyboard
} from 'react-native';
// import posts from "@/mock/posts";
import Mock from 'mockjs';
import { useSelector, useDispatch } from 'react-redux';
import { addComment, addGood, follow } from '@/store/postSlice';
import { Video } from 'expo-av';
import * as FileSystem from 'expo-file-system';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale'; // 导入中文本地化
import { router } from 'expo-router';
import { loadPosts } from '@/store/postSlice';
import store from "@/store/postindex";
const SCREEN_WIDTH = Dimensions.get('window').width;

export default function PostDetail({ route }) {
    // console.log(posts,'posts详情页打印');
    const { id } = route.params;
    const cid = '6'
    const dispatch = useDispatch();
    const posts = useSelector((state) => state.post.posts);
    useEffect(() => {
        store.dispatch(loadPosts()); // 加载存储的帖子
    }, [dispatch])
    // const postid = id
    // console.log("Post ID:", id);
    // const post = posts.find(p => p.id === id);
    const post = useSelector((state) =>
        state.post.posts.find((p) => p.id === id)
    );

    // useEffect(() => {
    //     console.log(post?.comments, 'Updated comments from Redux');
    // }, [post?.comments]);
    // const post = posts.find(p => String(p.id) === String(id));
    // if (!post) {
    //     console.error(`Post with ID ${id} not found!`);
    //     return <View>Error: Post not found!</View>;
    // }
    const postId = post.id
    const [comments, setComments] = useState(post.comments || [])
    // useEffect(() => {
    //     console.log(post.comments);
    // }, [])
    const [text, setText] = useState('');
    const textInputRef = useRef(null); // 使用 ref 引用 TextInput

    // 评论
    const AddComment = () => {
        if (text.trim()) {
            const newComment = {
                id: Mock.mock('@guid'),
                content: text, // 评论内容
                createTime: new Date().toISOString(), // 当前时间
                user: {
                    id: id, // 示例用户 ID（需要从登录状态中获取）
                    name: post.name, // 示例用户名
                    avatar: post.avatar, // 示例头像
                },
            }
            dispatch(addComment({ postid: post.id, comment: newComment }));
            // console.log(newComment, 'new');

            setComments((prevComments) => [newComment, ...prevComments]);
            setText(''); // 清空输入框
            Keyboard.dismiss(); // 隐藏键盘
            textInputRef.current.blur(); // 让 TextInput 失去焦点
            // console.log(post.comments, 'comments');
        }
    }
    useEffect(() => {
        if (!post) {
            // 如果没有找到帖子，可能是数据还没加载，处理这种情况
            return;
        }
    }, [post]); // 确保 post 数据加载完成后才执行

    const [mediaInfo, setMediaInfo] = useState({});
    const [likeStatus, setLikeStatus] = useState({}); // 管理每条帖子的点赞状态
    const [followedStatus, setFollowedStatus] = useState({}); // 管理每条帖子的关注状态
    const mediaExists = mediaInfo[post.media[0]?.uri] ?? false;
    // const relativeTime = formatDistanceToNow(new Date(item.createTime), { addSuffix: true });
    // 将 createTime 转换为 Date 对象
    const time = new Date(post.createTime);
    const isValidDate = !isNaN(time.getTime()); // 检查时间是否有效
    // const isLiked = likeStatus[post.id] || false; // 获取当前帖子的点赞状态
    const isLiked = post.goods.some((item) => item.id === cid)
    const isFollowed = post.fans.some((item) => item.id === cid)
    // const isFollowed = followedStatus[post.id] || false
    const [isLoading, setIsLoading] = useState(false); // 加载动画状态
    const [showFollowedMessage, setShowFollowedMessage] = useState(false); // "已关注" 提示框状态
    const [showMoreModal, setShowMoreModal] = useState(false); // 控制更多弹出框
    // 点赞和取消赞
    const handleLikeToggle = (postId) => {
        setLikeStatus((prev) => ({
            ...prev,
            [postId]: !prev[postId], // 切换对应帖子点赞状态
        }));
        const newGood = {
            id: id
        }
        dispatch(addGood({ postid: postId, good: newGood }))
    };
    // 点击关注按钮
    const handleFollow = (postId) => {
        setIsLoading(true); // 显示加载动画
        setTimeout(() => {
            setIsLoading(false); // 隐藏加载动画
            setShowFollowedMessage(true); // 显示"已关注"提示
            // 关注逻辑
            const newFocus = {
                id: postId
            }
            const newFans = {
                id: cid
            }
            dispatch(follow({ postid: postId, focus: newFocus, userId: cid, fans: newFans }))

            setFollowedStatus((prev) => ({
                ...prev,
                [postId]: true, // 设置该条数据为已关注
            }));

            setTimeout(() => {
                setShowFollowedMessage(false); // 隐藏"已关注"提示
            }, 2000);
        }, 2000);
    };
    // 点击更多
    const handleMoreModalToggle = () => {
        if (showMoreModal) {
            setShowMoreModal(false);
        } else {
            setTimeout(() => {
                setShowMoreModal(true);
            }, 100); // 延时，防止快速点击导致重复打开
        }
    };


    return (
        <View style={styles.container}>
            <ScrollView contentContainerStyle={styles.scrollContainer}>
                <View style={styles.header}>
                    <TouchableOpacity onPress={() => router.back()}>
                        <Image
                            source={require('../../assets/images/left.png')}
                            style={styles.backArrow}
                        />
                    </TouchableOpacity>
                    <View style={styles.imgsAndname}>
                        <Image source={{ uri: post.avatar }} style={styles.avatar} />
                        <View style={styles.nameAndgenderAndcountryAndtime}>
                            <View style={styles.genderAndname}>
                                <Text style={styles.name}>{post.name}</Text>
                                {post.gender === "男" ? (
                                    <Image
                                        source={require("../../assets/images/male.png")}
                                        style={styles.gender}
                                    />
                                ) : (
                                    <Image
                                        source={require("../../assets/images/female.png")}
                                        style={styles.gender}
                                    />
                                )}
                            </View>
                            <View style={styles.countryAndtime}>
                                <Text style={styles.location}>
                                    {/* <Translate i18nKey="United States">
                        </Translate> */}
                                    {post.country}
                                </Text>
                                {isValidDate ? (
                                    <Text style={styles.locations}>
                                        {formatDistanceToNow(time, { locale: zhCN })
                                            .replace("大约", "")
                                            .split(" ")}
                                        前
                                    </Text>
                                ) : (
                                    <Text style={styles.locations}>时间无效</Text>
                                )}
                            </View>
                        </View>
                    </View>
                    <View style={styles.imgs}>
                        {/* <TouchableOpacity>
                    <Image source={require('../../assets/images/plus.png')} style={styles.plus} />
                  </TouchableOpacity> */}
                        {!isFollowed && (
                            <TouchableOpacity onPress={() => handleFollow(post.id)}>
                                <Image
                                    source={require('../../assets/images/plus.png')}
                                    style={styles.plus}
                                />
                            </TouchableOpacity>
                        )}
                        <TouchableOpacity onPress={handleMoreModalToggle}>
                            <Image
                                source={require("../../assets/images/more.png")}
                                style={styles.more}
                            />
                        </TouchableOpacity>
                    </View>
                </View>
                {/* 循环展示头像 */}
                <FlatList
                    data={post.media}
                    keyExtractor={(item) => item.fileName}
                    showsVerticalScrollIndicator={false}
                    renderItem={({ item }) => {
                        return (
                            <View style={styles.mediaItem}>
                                {item.type === 'image' ? (
                                    <Image source={{ uri: item.uri }} style={styles.mediaPreview} />
                                ) : (
                                    <Video
                                        source={{ uri: item.uri }}
                                        rate={1.0}
                                        volume={1.0}
                                        isMuted={false}
                                        resizeMode="contain"
                                        shouldPlay={false}
                                        isLooping={false}
                                        style={styles.mediaPreview}
                                    />
                                )}
                            </View>

                        )
                    }}
                />

                <Text style={styles.postcontent}>{post.content}</Text>
                {/* 赞和评论 */}
                <View style={styles.goodAndComment}>
                    <View style={styles.goods}>
                        {
                            isLiked ? (
                                <TouchableOpacity onPress={() => handleLikeToggle(post.id)}>
                                    <Image source={require('../../assets/images/good.png')} style={styles.good} />
                                </TouchableOpacity>
                            ) : (
                                <TouchableOpacity onPress={() => handleLikeToggle(post.id)}>
                                    <Image source={require('../../assets/images/nogood.png')} style={styles.good} />
                                </TouchableOpacity>
                            )
                        }
                        <Text style={styles.goodNum}>{post.goods.length}人觉得很赞</Text>
                    </View>
                    <View style={styles.goodss}>
                        <TouchableOpacity>
                            <Image source={require('../../assets/images/comment.png')} style={styles.goodc} />
                        </TouchableOpacity>
                        <Text style={styles.commentNum}>{post.comments.length}</Text>
                    </View>
                </View>
                {/* 分割线 */}
                <View style={styles.line}></View>
                {/* 评论 */}
                <Text style={styles.commenttip}>评论</Text>

                {/* 评论列表 */}
                {
                    post.comments.length > 0 && (
                        <>
                            <FlatList
                                data={post.comments}
                                keyExtractor={(item) => item.id}
                                showsVerticalScrollIndicator={false}
                                renderItem={({ item }) => {
                                    const time = new Date(item.createTime);
                                    const isValidDate = !isNaN(time.getTime());
                                    return (
                                        <View style={styles.commentContainer}>
                                            <Image source={{ uri: item.user.avatar }} style={styles.avatar} />
                                            <View style={styles.commentContent}>
                                                <Text style={styles.userName}>{item.user.name}</Text>
                                                {/* <Text style={styles.createTime}>{item.createTime}</Text> */}
                                                {/* time */}
                                                {isValidDate ? (
                                                    <Text style={styles.createTime}>
                                                        {formatDistanceToNow(time, { locale: zhCN })
                                                            .replace("大约", "")
                                                            .replace("不到", "")
                                                            .split(" ")}
                                                        前
                                                    </Text>
                                                ) : (
                                                    <Text style={styles.locations}>时间无效</Text>
                                                )}
                                                <Text style={styles.content}>{item.content}</Text>
                                            </View>
                                        </View>
                                    )
                                }}
                            />
                            <Text style={styles.CommentEnd}>-已显示所有评论-</Text>
                        </>
                    )
                }
                {/* 暂无评论 */}
                {post.comments.length === 0 && (
                    <Text style={styles.noneComment}>-暂无评论-</Text>
                )}
            </ScrollView>
            {/* 评论吧 */}
            <View style={styles.containers}>
                <TextInput
                    style={styles.input}
                    ref={textInputRef} // 将 ref 绑定到 TextInput
                    placeholder="说点儿什么...."
                    placeholderTextColor="#ccc"
                    value={text}
                    onChangeText={setText}
                />
                <TouchableOpacity style={styles.iconButton}>
                    <Image
                        source={require('../../assets/images/emoji.png')} // 替换成你的表情图标
                        style={styles.icon}
                    />
                </TouchableOpacity>
                <TouchableOpacity
                    style={styles.iconButton}
                    onPress={AddComment}
                >
                    <Image
                        source={require('../../assets/images/send.png')} // 替换成你的发送图标
                        style={styles.icon}
                    />
                </TouchableOpacity>
            </View>
            {/* <KeyboardAvoidingView
                behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
                style={styles.containerss}
            >
                <View style={styles.inputBar}>
                    <TextInput
                        style={styles.input}
                        placeholder="说点儿什么...."
                        placeholderTextColor="#ccc"
                        value={text}
                        onChangeText={setText}
                    />
                    <TouchableOpacity style={styles.iconButton}>
                        <Image
                            source={{ uri: 'https://example.com/emoji-icon.png' }} // 替换为表情图标
                            style={styles.icon}
                        />
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.iconButton}>
                        <Image
                            source={{ uri: 'https://example.com/send-icon.png' }} // 替换为发送图标
                            style={styles.icon}
                        />
                    </TouchableOpacity>
                </View>
            </KeyboardAvoidingView> */}

            {/* 加载动画 */}
            {isLoading && (
                <Modal transparent>
                    <View style={styles.loadingOverlay}>
                        <ActivityIndicator size="large" color="#00C7B8" />
                    </View>
                </Modal>
            )}

            {/* "已关注" 提示 */}
            {showFollowedMessage && (
                <Modal transparent>
                    <View style={styles.messageOverlay}>
                        <View style={styles.messageBox}>
                            <Text style={styles.messageText}>已关注</Text>
                        </View>
                    </View>
                </Modal>
            )}
            {/* 更多操作弹出框 */}
            <Modal
                transparent
                visible={showMoreModal}
                animationType="slide"
                onRequestClose={() => setShowMoreModal(false)}
            >
                <TouchableOpacity
                    style={styles.modalOverlay}
                    activeOpacity={1} // 避免透明背景可点击后穿
                    onPress={() => { }} // 点击背景关闭弹出框
                >
                    <View style={styles.moreOptions}>
                        <TouchableOpacity
                            onPress={() => {
                                console.log('举报功能触发');
                                setShowMoreModal(false); // 关闭弹框
                                // 在这里可以调用 Redux action 或其他逻辑
                                Alert.alert('举报成功', '举报已提交');
                            }}
                        >
                            <Text style={styles.optionText}>举报</Text>
                        </TouchableOpacity>
                        <TouchableOpacity
                            onPress={() => {
                                console.log('屏蔽功能触发');
                                setShowMoreModal(false); // 关闭弹框
                                // 在这里可以调用屏蔽的逻辑
                                Alert.alert("屏蔽成功", '已屏蔽该用户');
                            }}
                        >
                            <Text style={styles.optionText}>屏蔽</Text>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={() => setShowMoreModal(false)}>
                            <Text style={[styles.optionText, styles.cancelText]}>取消</Text>
                        </TouchableOpacity>
                    </View>
                </TouchableOpacity>
            </Modal>
        </View>

    )
}
const styles = StyleSheet.create({
    // container: {
    //     flex: 1, // 允许ScrollView内容扩展并填满屏幕
    //     backgroundColor: "#f5f5f5",
    // },
    container: {
        flex: 1,
        flexDirection: 'column',
    },
    scrollContainer: {
        flexGrow: 1, // 允许ScrollView内容扩展并填满屏幕
        justifyContent: 'flex-start', // 垂直排列
    },
    header: {
        flexDirection: "row",
        // alignItems: 'center',
        marginBottom: 8,
        height: 50,
        marginTop: 10
    },
    backArrow: {
        // fontSize: 24,
        width: 18,
        height: 18,
        color: "#000",
        marginLeft: 10,
        paddingLeft: 25,
        marginTop: 20,
        marginRight: 5
    },
    nameAndgenderAndcountryAndtime: {
        marginTop: 5
    },
    imgsAndname: {
        flexDirection: "row",
        // alignItems: 'center',
        marginBottom: 4,
        // justifyContent: 'space-between',
        flex: 1,
    },
    plus: {
        width: 32,
        height: 20,
        borderRadius: 20,
        marginRight: 5
    },
    more: {
        width: 18,
        height: 22,
    },
    imgs: {
        flexDirection: 'row',
        height: 40,
        marginTop: 5
    },
    avatar: {
        width: 50,
        height: 50,
        borderRadius: 25,
        marginRight: 12,
    },
    genderAndname: {
        flexDirection: "row",
    },
    gender: {
        width: 20,
        height: 20,
        marginLeft: 5,
    },
    name: { fontWeight: "bold", fontSize: 16 },
    location: { fontSize: 12, color: "#666" },
    locations: { fontSize: 12, color: "#666", marginLeft: 8 },
    content: {
        fontSize: 14,
        color: "#333",
        marginBottom: 8,
    },
    mediaContainer: {
        marginTop: 8,
    },
    media: {
        width: SCREEN_WIDTH - 64,
        height: 200,
        borderRadius: 8,
        backgroundColor: "#ccc",
    },
    countryAndtime: {
        flexDirection: "row",
        // justifyContent: "space-between",
        marginTop: 4,
    },
    goodAndComment: {
        flexDirection: 'row',
        marginLeft: 10,
        // justifyContent: 'space-between',
        // width: 280
    },
    good: {
        width: 20,
        height: 20,
        marginLeft: 5,
        marginTop: 10
    },
    goodc: {
        width: 20,
        height: 20,
        marginLeft: 5,
        marginTop: 12
    },
    goods: {
        flexDirection: 'row',

    },
    goodss: {
        flexDirection: 'row',
        marginLeft: 10

    },
    goodNum: {
        fontSize: 12,
        color: '#666',
        marginLeft: 8,
        marginTop: 14
    },
    commentNum: {
        fontSize: 12,
        color: '#666',
        marginLeft: 8,
        marginTop: 14
    },
    loadingOverlay: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        // backgroundColor: 'rgba(0, 0, 0, 0.6)',
    },
    loadingText: {
        fontSize: 16,
        color: '#fff',
    },
    messageOverlay: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        // backgroundColor: 'rgba(0, 0, 0, 0.6)',
    },
    messageText: {
        fontSize: 14,
        color: '#ccc',
        marginTop: 10,
        marginLeft: 17
    },
    messageBox: {
        width: 80,
        height: 40,
        lineHeight: 40,
        textAlign: 'center',
        backgroundColor: 'rgb(0,0,0)',
        borderRadius: 10
    },
    modalOverlay: {
        flex: 1,
        backgroundColor: 'rgba(0, 0, 0, 0.1)',
        justifyContent: 'flex-end',
    },
    moreOptions: {
        backgroundColor: '#fff',
        padding: 16,
        borderTopLeftRadius: 12,
        borderTopRightRadius: 12,
    },
    optionText: {
        fontSize: 18,
        color: '#333',
        paddingVertical: 12,
        textAlign: 'center',
    },
    cancelText: {
        color: '#999',
        fontWeight: 'bold',
    },
    imagePreviewScroll: {
        alignItems: 'center',
    },
    imagePreviewContainer: {
        width: SCREEN_WIDTH,
        justifyContent: 'center',
        alignItems: 'center',
    },
    imagePreview: {
        width: SCREEN_WIDTH,
        height: 300,
        resizeMode: 'contain',
    },
    mediaItem: {},
    mediaPreview: {
        width: SCREEN_WIDTH - 20,
        height: 300,
        marginTop: 10,
        marginLeft: 10,
        borderRadius: 10
    },
    postcontent: {
        marginTop: 10,
        marginBottom: 10,
        fontSize: 16,
        color: '#333',
        marginLeft: 10
    },
    line: {
        width: SCREEN_WIDTH - 20,
        marginTop: 10,
        marginLeft: 10,
        height: 2,
        backgroundColor: '#EAEAEA',
        marginBottom: 10
    },
    commenttip: {
        fontSize: 18,
        fontWeight: 'bold',
        marginLeft: 10
    },
    commentContainer: {
        flexDirection: 'row',
        marginBottom: 20,
        padding: 10,
        // borderBottomWidth: 1,
        // borderBottomColor: '#ccc',
    },
    //   avatar: {
    //     width: 40,
    //     height: 40,
    //     borderRadius: 20,
    //     marginRight: 10,
    //   },
    commentContent: {
        flex: 1,
    },
    userName: {
        fontWeight: 'bold',
        fontSize: 16,
    },
    createTime: {
        fontSize: 12,
        color: '#888',
    },
    noneComment: {
        fontSize: 14,
        color: '#ccc',
        marginTop: 50,
        marginLeft: 10,
        marginBottom: 10,
        textAlign: 'center',
        height: 100
    },
    CommentEnd: {
        fontSize: 14,
        color: '#ccc',
        marginTop: 10,
        marginLeft: 10,
        marginBottom: 10,
        textAlign: 'center',
        height: 40
    },
    containers: {
        flexDirection: 'row',
        alignItems: 'center',
        position: 'sticky',
        bottom: 0,
        left: 0,
        right: 0,
        backgroundColor: '#f4f4f4',
        paddingVertical: 10,
        paddingHorizontal: 15,
        borderTopWidth: 1,
        borderTopColor: '#e0e0e0',
    },
    input: {
        flex: 1,
        height: 40,
        backgroundColor: '#fff',
        borderRadius: 20,
        paddingHorizontal: 15,
        fontSize: 16,
        color: '#000',
        marginRight: 10,
    },
    iconButton: {
        padding: 5,
    },
    icon: {
        width: 24,
        height: 24,
    },
    // containerss: {
    //     flex: 1,
    //     justifyContent: 'flex-end', // 确保内容位于底部
    //   },
    //   inputBar: {
    //     flexDirection: 'row',
    //         alignItems: 'center',
    //         position: 'absolute',
    //         bottom: 0,
    //         left: 0,
    //         right: 0,
    //         backgroundColor: '#f4f4f4',
    //         paddingVertical: 10,
    //         paddingHorizontal: 15,
    //         borderTopWidth: 1,
    //         borderTopColor: '#e0e0e0',
    //   },
    //   input: {
    //     flex: 1,
    //     height: 40,
    //     backgroundColor: '#fff',
    //     borderRadius: 20,
    //     paddingHorizontal: 15,
    //     fontSize: 16,
    //     color: '#000',
    //     marginRight: 10,
    //   },
    //   iconButton: {
    //     padding: 5,
    //   },
    //   icon: {
    //     width: 24,
    //     height: 24,
    //   },
})
